﻿<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<LeanBoard.Models.ItemsCollection>" %>
<%@ Import Namespace="LeanBoard.HtmlBuilders" %>
<%@ Import Namespace="System.Web.Configuration" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title><%= "Smartboard READONLY - " + Model.TeamName %></title>
    <link href="/Client/base.css" rel="stylesheet" type="text/css" />
    <!--Left for the RELEASE, for DEV use localy referenced-->
    <!--<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script> 
	<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/jquery-ui.min.js" type="text/javascript"></script> 
    <script src="http://cdn.jquerytools.org/1.2.3/all/jquery.tools.min.js" type="text/javascript"></script>-->

    <script src="/Scripts/jquery-1.4.2.js" type="text/javascript"></script>
    <script src="/Scripts/jquery-ui.js" type="text/javascript"></script>
    <script src="/Scripts/jquery.tools.min.js" type="text/javascript"></script>
    <script src="/Scripts/jquery.keypad.min.js" type="text/javascript"></script>

    <script type="text/javascript">
        $(document).ready(function () {
            $("#devstatus").click(function () { if (failedSmokeTestsMessages["Dev"] != "") showAlert(failedSmokeTestsMessages["Dev"]); });
            $("#teststatus").click(function () { if (failedSmokeTestsMessages["Test"] != "") showAlert(failedSmokeTestsMessages["Test"]); });
            $("#buildstatus").click(function () { if (failedBuildMessage != "") showAlert("Failing builds:" + failedBuildMessage) });

            $('#notification').ajaxStart(function () {
                $(this).removeAttr('class').addClass('statusWorking').html('Working...').fadeIn();
            });

            $('#notification').ajaxSuccess(function () { });            

            /*$("#scheduled, #analysis, #analysisReadyForReview, #analysisReview, #failedInTest, #readyForDevelopment,  #development, #readyForCodeReview, #codeReview, #readyForApproval, #testing").sortable({ connectWith: '.list', placeholder: 'placeholder cr', opacity: '0.5', handle: '.handle',
                receive: function (event, ui) {
                    $.post(
                    "/leanboard/Move", getValue(ui.item), function (data) {
                        $('#notification').removeAttr('class').addClass('status' + data.Status).html(data.Message).delay(3000).fadeOut().delay(500);
                        if (data.Status == 'Failure') {
                            $(ui.sender).sortable('cancel');
                        }
                        else {
                            writeWip();
                            evaluateColumnItems();
                            updateItemStatus(ui.item);

                            location.reload(false);
                        }
                    });
                }
            }).disableSelection();*/

            $('#standup .items').ready(function () {
                if ($('#standup .itemPopup', $(this)).length > 0) {
                    $("#standup .scrollable").scrollable({ size: 1, next: '.next', prev: '.prev', circular: true });
                }
            });

            $("#teamName").overlay({ speed: 0, closeSpeed: 0, close: '.close', target: '#standup', top: 'center', closeOnClick: false, mask: { color: '#444444', loadSpeed: 0, closeSpeed: 0, opacity: '0.55'} });

            $("li").each(function () {
                $(this).find('.content').overlay({ speed: 0, closeSpeed: 0, close: '.close', target: '#singleOverlay' + $(this).find('.itemUnid').text(), top: 'center', closeOnClick: false, mask: { color: '#444444', loadSpeed: 0, closeSpeed: 0, opacity: 0.55} });
            });

            $('#chooseTeam').click(function () {
                var currentMode = $(this).attr('class').indexOf('collapsed');
                if (currentMode > -1) {
                    $(this).html('&#9660;');
                    $('#chooseTeamPopup').show();
                }
                else {
                    $(this).html('&#9654;');
                    $('#chooseTeamPopup').hide();
                }
                $(this).toggleClass('collapsed');
            });

            /*$(".itemPopup .profileImage").click(function () {
                var itemPopup = $(this).parent();
                var itemId = itemPopup.attr('id').replace(/\D/gi, "");
                $("#responsibleSelector #relatedItemId").text(itemId);
                $("#responsibleSelector").show();
            });*/

            /*$("#responsibleSelector .profileImage").click(function () {
                var newResponsible = $(this).find("h2").text();
                var itemId = $("#responsibleSelector #relatedItemId").text();
                var unid = $("#" + itemId).find(".itemUnid").text();
                var status = $("#" + itemId).closest("ul").attr('id');
                var itemType = $("#" + itemId).attr('class');
                
                $.post(
                    "/leanboard/Assign", ({ itemUnid: unid, name: newResponsible, leanStatus: status, type: itemType }), function (data) {
                        $('#notification').removeAttr('class').addClass('status' + data.Status).html(data.Message).delay(5000).fadeOut().delay(500);
                    });

                $("#all" + itemId).find(".profileImage > img").attr("src", "/ProfileImage/GetImage/?imageProfile=" + newResponsible.replace(" ", "") + ".jpg");
                $("#standup" + itemId).find(".profileImage > img").attr("src", "/ProfileImage/GetImage/?imageProfile=" + newResponsible.replace(" ", "") + ".jpg");
                $("#all" + itemId).find(".profileImage > h2").text(newResponsible);
                $("#standup" + itemId).find(".profileImage > h2").text(newResponsible);
                $("#" + itemId).find(".crResponsible").text(newResponsible);
                $("#relatedItemId").text("");
                $("#responsibleSelector").hide();
            });*/

            $("#responsibleSelector .cancel").click(function () {
                $("#relatedItemId").text("");
                $("#responsibleSelector").hide();
            });

            $("#standup .details").click(function () {
                var index = $("#standup .scrollable").scrollable().getIndex() + 1;
                var itemUnid = $($("#standup .scrollable .items .itemPopup").get(index)).find(".itemUnid").html();
                viewDetailsForUnid($(this), itemUnid);
            });

            $("#standup .overview").click(function () {
                setChildElementsVisibilityForOverview($(this).parent());
            });

            $("#allItems .details").click(function () {
                var itemUnid = $(this).parent().find(".itemUnid").html();
                viewDetailsForUnid($(this), itemUnid);
            });

            $("#allItems .overview").click(function () {
                setChildElementsVisibilityForOverview($(this).parent());
            });

            $("#search").keypad({ keypadClass: 'darkKeypad', keypadOnly: false, layout: $.keypad.qwertyLayout, prompt: '', showAnim: '' });
            $("#search").change(function () { filterChangeRequests(); });
            $("#search").keyup(function () { filterChangeRequests(); });

            $("#searchArea span").click(function () {
                $("#searchArea input").val('');
                filterChangeRequests();
            });

            $(window).resize(function () {
                fitBoardHeight();
            });

            updateBuildStatus();
            fitBoardHeight();
            writeWip();
            evaluateColumnItems();
            timedRefreshSampler();
        });

        var currentlyFailedBuilds = 0;
        var failedBuildMessage = "";
        var failedSmokeTestsMessages = [];
        var overlayIsOpened;
        var timer = 0;

        var statusArray = [];
        statusArray["#scheduled"] = "Scheduled";
        statusArray["#analysis"] = "Analysis";
        statusArray["#analysisReadyForReview"] = "Ready for analysis review";
        statusArray["#analysisReview"] = "Analysis review";
        statusArray["#readyForDevelopment"] = "Ready for development";
        statusArray["#development"] = "Development";
        statusArray["#readyForCodeReview"] = "Ready for Code Review";
        statusArray["#codeReview"] = "Code Review";
        statusArray["#readyForApproval"] = "Ready for Approval";
        statusArray["#testing"] = "Testing";
        statusArray["#done"] = "Done";

        function timedRefreshSampler() {
            // check standup
            overlayIsOpened = $("#teamName").data('overlay').isOpened() || $("#keypad-div").is(':visible') || $("#search").val() != "";
            // check all other
            if (overlayIsOpened != true)
            {
                $("li").each(function () {
                    overlayIsOpened = $(this).find('.content').data('overlay').isOpened();
                    if (overlayIsOpened == true) {
                        return false;
                    }
                });
            }
            
            timer = timer + 1;
            if (timer > 59)
            {
                location.reload(false);
            }
            else
            {
	            setTimeout("if (overlayIsOpened == true) { timer = 0; } timedRefreshSampler();", 1000);
            }
            
        }

        function updateSmoketestStatus(env) {
            var statusServerUrl = "";
            if(env.toLowerCase() == "dev"){
                statusServerUrl = "http://<%= WebConfigurationManager.AppSettings["dev_status_server_url"] %>?callback=?";
            }
            else if(env.toLowerCase() == "test")
            {
                statusServerUrl = "http://<%= WebConfigurationManager.AppSettings["test_status_server_url"] %>?callback=?";
            }
            jQuery.getJSON(statusServerUrl,
            function (data) {
                var smokeTestEnv = env + "_Smk";
                var status = $("#" + env.toLowerCase() + "status");
                var currentlyFailedTests = data.length;
                if (currentlyFailedTests == 0) {
                    status.removeClass("fail");
                    status.html(smokeTestEnv);
                    failedSmokeTestsMessages[env] = "";                  
                }
                else {
                    status.addClass("fail");
                    status.html(smokeTestEnv + "(" + data.length + ")");

                    failedSmokeTestsMessages[env] = "";
                    jQuery.each(data, function (index) {
                        failedSmokeTestsMessages[env] += "<div>" + data[index] + "</div>"
                    });
                    showAlert(failedSmokeTestsMessages[env]);
                }
                $('#notification').removeAttr('class').addClass('statusSuccess').html('Done').delay(3000).fadeOut().delay(500);
            });
        }

        function updateBuildStatus() {
            jQuery.getJSON("http://<%= WebConfigurationManager.AppSettings["build_status_server_url"] %>?callback=?",
            function (data) {
                var unfilteredbuilds = data;
                var builds = new Array();
                $.each(unfilteredbuilds, function (i, build) {
                    if (build.project.indexOf("Archive") == -1) builds.push(build);
                });
                var status = jQuery("#buildstatus");
                if (builds.length == 0) {
                    currentlyFailedBuilds = 0;
                    status.removeClass("fail");
                    failedBuildMessage = "";
                } else {
                    status.addClass("fail");
                    /*status.html("B: " + builds.length + " F");*/
                    if (currentlyFailedBuilds != builds.length) {
                        currentlyFailedBuilds = builds.length;
                        var ar = new Array();
                        for (var i in builds) {
                            ar.push("<div>" + builds[i].project + " (" + builds[i].branch + ")</div>");
                        }
                        failedBuildMessage = ar.join("");
                        showAlert("Failing builds:" + failedBuildMessage);
                    }
                }
                $('#notification').removeAttr('class').addClass('statusSuccess').html('Done').delay(3000).fadeOut().delay(500);
            });
            updateSmoketestStatus("Dev");
            //updateSmoketestStatus("Test");
        }

        function showAlert(message) {
            var msgBox = $("#alertMessage");
            msgBox.stop().html(message).show().css({ opacity: 1 });
            msgBox.css("left", ($(window).width() - msgBox.outerWidth()) / 2).css("top", ($(window).height() - msgBox.outerHeight()) / 2);
            setTimeout(hideAlert, 5000);
        }

        function hideAlert() {
            $("#alertMessage").animate({ opacity: 0 }, 1000, function () { $("#alertMessage").hide(); })
        }

        /*function blink(element) {
            element.stop(true, true).fadeOut().fadeIn().fadeOut().fadeIn();
        }*/

        function getValue(item) {
            return { Id: $(item).find("itemNumber").html(), DevResponsible: $(item).find(".crResponsible").html(), QaResponsible: $(item).find(".crQAResponsible").html(), Status: $(item).parent().attr("id"), Unid: $(item).find(".itemUnid").html() };
        }

        function filterChangeRequests() {
            var searchTerm = $("#search").val().toLowerCase();
            $("li[id]").each(function () {
                if (this.innerHTML.toLowerCase().indexOf(searchTerm) == -1) {
                    $(this).fadeOut(10);
                }
                else
                { $(this).fadeIn(10); }
            });
        }

        function viewDetailsForUnid(sender, itemUnid) {
            var iFrameHtml = getIFrameHtml(itemUnid);
            setChildElementsVisibilityForDetails(sender.parent());
            sender.parent().find(".externalContentFrame").html(iFrameHtml);
        }

        function getIFrameHtml(unid) {
            var iFrame = $('<iframe class="itemPopup"></iframe>');
            var link = 'http://<%= WebConfigurationManager.AppSettings["data_server_url"] %>/wvwUNID/' + unid + '?OpenDocument';
            $(iFrame).attr({ src: link });
            return iFrame;
        }

        function setChildElementsVisibilityForOverview(parentElement) {
            parentElement.find(".scrollable").show();
            parentElement.find(".itemPopup").show();
            parentElement.find(".externalContentFrame").hide();
            parentElement.find(".prev").show();
            parentElement.find(".overview").hide();
            parentElement.find(".next").show();
            parentElement.find(".details").show();            
        }

        function setChildElementsVisibilityForDetails(parentElement) {
            parentElement.find(".scrollable").hide();
            parentElement.find(".itemPopup").hide();
            parentElement.find(".externalContentFrame").show();
            parentElement.find(".prev").hide();
            parentElement.find(".overview").show();
            parentElement.find(".next").hide();
            parentElement.find(".details").hide();
        }

        function fitBoardHeight() {
            $('.column').css('height', $(window).height() - 67);
            $('.list').css('height', $(window).height() - 117);
            $('.listsplit').css('height', $(window).height()/2 - 117);
        }

        function writeWip(){
            var currentWip = getWipCount();
            var maxWip = <%= new ItemHtmlBuilder().GetWip(Model.TeamName) %>;
            $('#wipCount').html('WIP ' + currentWip + '/' + maxWip);
            if (currentWip > maxWip){
                $('#wipCount').css('background-color','red');
            }
            else {
                $('#wipCount').css('background-color','transparent');
            }
        }

        function evaluateColumnItems()
        {
            $(".column").each(function(index)
            {
                var h2 = $(this).find("h2").each(function(){
                    var itemsPerList = $(this).next("ul").find("li").length;
                    $(this).html( $(this).html().replace(/\d+/gi, itemsPerList) );
                });
            });
        }

        function updateItemStatus(item)
        {
            var itemNumber = $(item).find(".itemNumber").html();
            var aboutToBeReplaced = $("#all" + itemNumber).find(".itemInfo:first-child").text();
            var prefixEndIndex = aboutToBeReplaced.indexOf('-') + 2;
            var newStatusString = statusArray["#"+$(item).parent().attr("id")];
            var newText = aboutToBeReplaced.substring(0,prefixEndIndex) + newStatusString;
            
            $("#all" + itemNumber).find(".itemInfo").text(newText);
            $("#standup" + itemNumber).find(".itemInfo").text(newText);
        }

        function getWipCount() {
            return $('li', '#development, #failedInTest, #readyForCodeReview, #codeReview, #readyForApproval, #testing').length;
        }
	</script>

</head>
<body>
    <div class="main">
        <div id="statusBar">
            <div id="responsibleSelector">
                <span id="relatedItemId" style="display:none;"></span>
                <%= new ItemHtmlBuilder().BuildResponsiblesGallery(Request.PhysicalApplicationPath) %>
                <div class="cancel">Cancel</div>
            </div>
            <div id="notificationContainer">
                <div id="notification" class="statusSuccess">Ready<br />Steady</div>
            </div>
        
            <div id="searchArea">
              <% using (Html.BeginForm()) { %>
                   <%= Html.TextBox("search")%>
                   <span class="button">Clear</span>
              <% } %>
            </div>

            <div id="chooseTeamPopup">
                <%= new ItemHtmlBuilder().BuildTeamUrls(true) %>
            </div>
         
            <h1 id="chooseTeam" class="bigHeader collapsed leftFloat">&#9654</h1>        
            <h1 id="teamName" class="bigHeader"><%= new ItemHtmlBuilder().GetTeamDisplayName(Model.TeamName, Model.ReleaseDate)%></h1>        
            <h1 id="wipCount" class="bigHeader"></h1>        
            <h1 id="buildstatus" class="bigHeader">Build</h1>
            <h1 id="devstatus" class="bigHeader">Dev_Smk</h1>            
            <h1 id="teststatus" class="bigHeader">Test_Smk</h1>            
        </div>
        <div id="board">
            <div id="groupHeaders">
                <h1 class="columnGroup groupScheduled columnHeader">Scheduled</h1>
                <h1 class="columnGroup groupAnalysis columnHeader leftBorderSolid">Analysis</h1>
                <h1 class="columnGroup groupDevelopment columnHeader leftBorderSolid">Development</h1>
                <h1 class="columnGroup groupTesting columnHeader leftBorderSolid">Testing</h1>
            </div>
            <div class="column scheduledGroup">
                <h2 class="columnHeader">Queue<br /> ( <%= Model.Scheduled.Count%> )</h2>
                <ul id="scheduled" class="list">
                    <%= new ItemHtmlBuilder().BuildBoardItemsHtml(Model.Scheduled) %>
                </ul>
            </div>
            <div class="column analysisGroup leftBorderSolid">
                <h2 class="columnHeader">In Progress <br />( <%= Model.Analysis.Count%> )</h2>
                <ul id="analysis" class="list">
                    <%= new ItemHtmlBuilder().BuildBoardItemsHtml(Model.Analysis) %>
                </ul>
            </div>
            <div class="column analysisGroup">
                <h2 class="columnHeader">Ready for <br /> ( <%= Model.AnalysisReadyForReview.Count%> )</h2>
                <ul id="analysisReadyForReview" class="list leftBorderDotted">
                    <%= new ItemHtmlBuilder().BuildBoardItemsHtml(Model.AnalysisReadyForReview) %>
                </ul>
            </div>
            <div class="column analysisGroup">
                <h2 class="columnHeader">Review <br />( <%= Model.AnalysisReview.Count%> )</h2>
                <ul id="analysisReview" class="list leftBorderDotted">
                    <%= new ItemHtmlBuilder().BuildBoardItemsHtml(Model.AnalysisReview) %>
                </ul>
            </div> 
            <div class="column developmentGroup leftBorderSolid">
                <h2 class="columnHeader">Ready for <br /> ( <%= Model.ReadyForDevelopment.Count%> )</h2>
                <ul id="readyForDevelopment" class="listsplit">
                    <%= new ItemHtmlBuilder().BuildBoardItemsHtml(Model.ReadyForDevelopment) %>
                </ul>
                <h2 class="columnHeader">Failed <br /> ( <%= Model.Failed.Count%> )</h2>
                <ul id="failedInTest" class="listsplitfailed">
                    <%= new ItemHtmlBuilder().BuildBoardItemsHtml(Model.Failed) %>
                </ul>
            </div>
            <div class="column developmentGroup">
                <h2 class="columnHeader">Development <br /> ( <%= Model.Development.Count%> )</h2>
                <ul id="development" class="list leftBorderDotted">
                    <%= new ItemHtmlBuilder().BuildBoardItemsHtml(Model.Development) %>
                </ul>
            </div>
            <div class="column developmentGroup">
                <h2 class="columnHeader">Ready for <br /> ( <%= Model.ReadyForCodeReview.Count%> )</h2>
                <ul id="readyForCodeReview" class="list leftBorderDotted">
                    <%= new ItemHtmlBuilder().BuildBoardItemsHtml(Model.ReadyForCodeReview) %>
                </ul>
            </div>
            <div class="column developmentGroup">
                <h2 class="columnHeader">Code Review <br /> ( <%= Model.CodeReview.Count%> )</h2>
                <ul id="codeReview" class="list leftBorderDotted">
                    <%= new ItemHtmlBuilder().BuildBoardItemsHtml(Model.CodeReview) %>
                </ul>
            </div>
            <div class="column testingGroup leftBorderSolid">
                <h2 class="columnHeader">Ready for <br /> ( <%= Model.ReadyForApporval.Count%> )</h2>
                <ul id="readyForApproval" class="list">
                    <%= new ItemHtmlBuilder().BuildBoardItemsHtml(Model.ReadyForApporval) %>
                </ul>
            </div>
            <div class="column testingGroup">
                <h2 class="columnHeader">Testing <br /> ( <%= Model.Testing.Count%> )</h2>
                <ul id="testing" class="list leftBorderDotted">
                    <%= new ItemHtmlBuilder().BuildBoardItemsHtml(Model.Testing) %>
                </ul>
            </div>            
            <div class="column testingGroup">
                <h2 class="columnHeader">Done <br /> ( <%= Model.Done.Count%> )</h2>
                <ul id="done" class="list leftBorderDotted">
                    <%= new ItemHtmlBuilder().BuildBoardItemsHtml(Model.Done) %>
                </ul>
            </div>
        </div>
    </div>    

    <div id="alertMessage" class="" style=""></div>

    <div id="standup" class="apple_overlay standupBody">
        <div class="button prev">< Previous</div>
        <div class="button overview">Overview</div>
        <div class="button next">Next ></div>
        <div class="button details">Details</div>
        <div class="button close">Close</div>
        <div class="scrollable">
            <div class="items">
                <%= new ItemHtmlBuilder().BuildStandupItems(Model) %>
            </div>
        </div>
        <div class="externalContentFrame"></div>
    </div>

    <div id="allItems">
        <%= new ItemHtmlBuilder().BuildAllItems(Model) %>
    </div>
</body>
</html>
